package tech.aistar.interceptor;


import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.aistar.model.dto.Code;
import tech.aistar.model.dto.Result;
import tech.aistar.model.entity.Customer;
import tech.aistar.util.JWTUtils;

import java.io.PrintWriter;

/**
 * 本来用来演示:
 *
 * @author success
 * @date 2023/3/2 15:28:03
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头信息中的token值
        String token = request.getHeader("token");
        //如果请求头信息中没有token,返回null
        System.out.println("token+++++++++:"+token);
        if(null==token){
            //说明没有登录
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();

            out.print(JSON.toJSONString(new Result(Code.BAD,"sorry,先去登录吧!")));
            return false;
        }else{
            //token是存在的.  可能是一个非法的token,claims是返回的是null
            Claims claims = JWTUtils.checkJWT(token);
            if(null==claims){
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();

                out.print(JSON.toJSONString(new Result(Code.WRONG,"sorry,非法token!")));
                return false;
            }else{
                //token是合法的.
                Integer id = (Integer) claims.get("id");
                String username = (String) claims.get("username");


                //request.setAttribute("username",username);
                Customer c=new Customer();
                c.setId(id);
                c.setName(username);
                redisTemplate.opsForValue().set("currUser",c);


                return true;
            }
        }
    }
}
